const express = require('express')
const router = express.Router()
const { count, findAll, detail, insert, update } = require('@/dao/TagDao')

router.get('/', async (req, res) => {
  const total = await count()
  const data = await findAll(req)
  if (data.code && data.code.indexOf('ER') !== -1) return res.sendResult([], _code.OPE, '请求失败，请稍后再试')
  const result = {
    total: total[0].count,
    rows: data
  }
  res.sendResult(result, _code.GDS, '请求成功')
})

router.get('/detail', async (req, res) => {
  const data = await detail(req)
  if (data.code && data.code.indexOf('ER') !== -1) return res.sendResult([], _code.OPE, '请求失败，请稍后再试')
  if (data.length === 0) res.sendResult(null, _code.GDE, '未找到该标签')
  else res.sendResult(data[0], _code.GDS, '请求成功')
})

router.post('/insert', async (req, res) => {
  const data = await insert(req)
  if (data.code && data.code.indexOf('ER') !== -1) return res.sendResult(null, _code.OPE, data)
  // if (data.code && data.code.indexOf('ER') !== -1) return res.sendResult(null, _code.OPE, '操作失败，请稍后再试')
  res.sendResult(data.insertId, _code.OPS, '添加成功')
})

router.put('/update', async (req, res) => {
  const data = await update(req)
  if (data.code && data.code.indexOf('ER') !== -1) return res.sendResult(null, _code.OPE, '操作失败，请稍后再试')
  res.sendResult(data, _code.OPS, '修改成功')
})

router.delete('/remove', async (req, res) => {
  const data = await remove(req)
  if (data.code && data.code.indexOf('ER') !== -1) return res.sendResult(null, _code.OPE, '删除失败，请稍后再试')
  res.sendResult(req.body.id, _code.OPS, '删除成功')
})

module.exports = router;